package com.crm.controller.invoiceController;

import java.io.ByteArrayOutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.crm.dao.AttachmentHistoryDAO;
import com.crm.dao.ClientdetDAO;
import com.crm.dao.DeliveryChallanDAO;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.StockDAO;
import com.crm.dao.SupplyOrderDAO;
import com.crm.entity.AttachmentHistory;
import com.crm.entity.Business;
import com.crm.entity.Clientdet;
import com.crm.entity.DeliveryChallan;
import com.crm.entity.Opportunity;
import com.crm.entity.Parts;
import com.crm.entity.Quotation;
import com.crm.entity.SupplyOrder;
import com.crm.util.Constants;

@Controller
@RequestMapping("/deliveryChallan")
public class DeliveryChallanController {
	protected final Log logger = LogFactory.getLog(getClass());
	
	//OpportunityDAO opportunityDAO=new OpportunityDAO();
	QuotationDAO quotationDAO=new QuotationDAO();
	DeliveryChallanDAO dcDAO=new DeliveryChallanDAO();
	PartsDAO partsDAO=new PartsDAO();
	SupplyOrderDAO supplyOrderDAO=new SupplyOrderDAO();
	AttachmentHistoryDAO attachmentDAO = new AttachmentHistoryDAO();
	ClientdetDAO clientdetDAO=new ClientdetDAO();
	StockDAO stockDao=new StockDAO();
	@RequestMapping("/open.do")
	public ModelAndView show(ModelAndView model,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		String status=Constants.ST_GENERATED_INVOICE;
		List<Opportunity> opp=OpportunityDAO.getSingleInstance().getByStatus(status, busid);
		return model=new ModelAndView("/jsp/Delivery Challan.jsp")
		.addObject("menuName","invoice")
		.addObject("submenu","invoice")
		.addObject("oppList",opp);
	}
	@RequestMapping( "/printdc.do") 
	public ModelAndView printpi(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
			List<AttachmentHistory> attlist=null;
			try{attlist=attachmentDAO.getAllPi(bus.getBusinessId(),Constants.DELIVERY_CHALLAN);
					logger.info("attachment list is "+attlist);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			  model = new ModelAndView("/jsp/printDC.jsp");
				model.addObject("attlist",attlist);
				model.addObject("submenu", "invoice");
				model.addObject("menuName","invoice");
				 
		 
				return model;
	}
	
	
	@RequestMapping(value = "/get_dc.do", method = RequestMethod.GET)
	public String pinting(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus = (Business) session.getAttribute("business");

		String idno = request.getParameter("quotid");
		int id=Integer.parseInt(idno);
		
		AttachmentHistory att = attachmentDAO.getAttachmentHistoryByPI(id);
		logger.info("the business id is  " + bus.getBusinessId());
		byte[] pdfReport = att.getFileBlob();
		logger.info("the length of pdf is" + pdfReport.length);
		logger.info("the length of pdf is" + pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		String fileName = "quotation.doc";
		response.setHeader("Content-Disposition", "inline; filename=" + fileName);
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close();
		return null;

	}
	@RequestMapping("/getDC.do")
	public ModelAndView getDC(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		logger.info("In DC Controller");
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		String refno=request.getParameter("refList");
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid, refno);
		logger.info("RefNo In Controller Is:"+refno);
		Clientdet clientdet=null;
		clientdet=o.getClientId();
		clientdet.setDivision(o.getDivision());
		int enqid=o.getId();
		logger.info("Enquiry Id Is:"+enqid);
		List<Quotation> lob = null;
		try {
			lob=quotationDAO.getquot(enqid);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		List<Parts> lsp=new ArrayList<Parts>();
		Iterator<Quotation> it=lob.iterator();
		int quotid=0;
		while(it.hasNext()){
			if(lob!=null){
				Object ob=it.next();
				Quotation q=(Quotation)ob;
				quotid=q.getId();		
				logger.info("Quotation Id Inside Iterator Is:"+quotid);
			}
			logger.info("Quotation Id Is:"+quotid);
			List<SupplyOrder> liso=null;
			try {
				liso=supplyOrderDAO.getByQuotid(busid,quotid);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			java.util.Iterator<SupplyOrder> itr=liso.iterator();
			logger.info("Supply Order List Is:"+liso);
			while(itr.hasNext()==true){
				Object ob=itr.next();
				SupplyOrder so=(SupplyOrder)ob;
				int partid=so.getPrtid();
				logger.info("Part id Is:"+partid);
				Parts p=new Parts();
				p=partsDAO.findByPartIdEnqId(enqid,partid, busid);
				if(p!=null){
					System.out.println("Part Description In Controller is:"+p.getDescription());
					lsp.add(p);
				}
			}
			
		}
		
		
		List<SupplyOrder> lisup=supplyOrderDAO.getByQuotid(busid, quotid);
		String soNo=null;
		Date soDate=null;
		Iterator<SupplyOrder> ite=lisup.iterator();
		System.out.println("supplyodrder date is"+lisup);
		while(ite.hasNext()==true){
			SupplyOrder sup=(SupplyOrder)ite.next();
			soNo=sup.getSuplyOrderNum();
			soDate=sup.getDate();
			System.out.println("supplyodrder date is"+soDate);
		}
		
		SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
		String da=sdf.format(soDate);
		
		
		DeliveryChallanDAO dcDAO=new DeliveryChallanDAO();
		String temp[]=refno.split("/");
		Long count=dcDAO.getDCCount(busid);
		String challanno=temp[0]+"/"+temp[1]+"/"+count+"/"+temp[3];
		logger.info("challan No Is:"+challanno);
		logger.info("partsList Is:"+lsp);
		logger.info("soDate Is:"+soDate);
		logger.info("soNo Is:"+soNo);
		return model=new ModelAndView("/jsp/DeliveryChallanRes.jsp")
		.addObject("challanNO",challanno)
		.addObject("partsList",lsp)
		.addObject("soNumber",soNo)
		.addObject("soDate",da)
		.addObject("client",clientdet)
		.addObject("user",o.getUser());
	}
	@RequestMapping("/saveDC.do")
	public ModelAndView saveDC(ModelAndView model,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		
		
		
		String refno=request.getParameter("refList");
		
		String sono=request.getParameter("soNumber");
		String challanno=request.getParameter("challanNo");
		String soDate=request.getParameter("soDate");
		Opportunity op=OpportunityDAO.getSingleInstance().getByRefNo(busid, refno);
		List<Quotation> lob = null;
		try {
			lob = quotationDAO.getquot(op.getId());
			
		}catch(NullPointerException e){
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		int quotid=0;
		Iterator<Quotation> itr=lob.iterator();
		while(itr.hasNext()==true){
			Object ob=itr.next();
			Quotation q=(Quotation)ob;
			quotid=q.getId();
		}
		Date date=new java.sql.Date(new java.util.Date().getTime());
		DeliveryChallan dc=new DeliveryChallan(quotid,sono,date,challanno,bus);
		
		
		

		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid, refno);

		int enqid=o.getId();
		String quotby=bus.getBusinessName();
		Quotation quotation=quotationDAO.getPendingQuot(enqid, busid);
		
		 List<com.crm.beans.QuotParts> lst=new ArrayList<com.crm.beans.QuotParts>();
		 int rowCount=Integer.parseInt(request.getParameter("rowCount"));
			List<Parts> partsList=new ArrayList<Parts>();
			
		for(int i=0;i<rowCount;i++){
			//Parts par=new Parts();
			String prtnum=request.getParameter("partNumber"+(i+1));
			String desc=request.getParameter("desc"+(i+1));
			String sqty=request.getParameter("qty"+(i+1));
			
			int partId=Integer.parseInt(request.getParameter("partId"+(i+1)));
			int quantity=Integer.parseInt(request.getParameter("qty"+(i+1)));
			Parts p=new Parts(partId,quantity);
			partsList.add(p);
			
			int qty=Integer.parseInt(sqty);
			
			List<SupplyOrder> lso=null;
			try {
				lso=supplyOrderDAO.findByQIdPrtId(quotation.getId(), partId, busid);
			} catch (Exception e) {
				e.printStackTrace();
			}
			int bal=0;
			if (lso!=null) {
				Iterator<SupplyOrder> ite = lso.iterator();
				while (ite.hasNext() == true) {
					Object obj = ite.next();
					SupplyOrder sop = (SupplyOrder) obj;
					if (sop.getQty() != qty && qty > sop.getQty()) {
						bal = qty - sop.getQty();
					} else if (sop.getQty() != qty && qty < sop.getQty()) {
						bal = sop.getQty() - qty;
					}
					logger.info("Balance Is :" + bal);
				}
			}
			
			com.crm.beans.QuotParts qp=new com.crm.beans.QuotParts(prtnum,sqty,"","","1","","", (i+1)+"",desc,"");
			logger.info("part "+qp);
			lst.add(qp);
		}
		
		stockDao.deleteStock(partsList,busid);
		
		  Map<String,String> parms = new HashMap<String,String>();
		 parms.put("challanno", challanno);
		 parms.put("sonumber", sono);
		 parms.put("sodate",soDate);
		 parms.put("customer",o.getClientId().getAddr());
		 parms.put("from",quotby);
		 session= request.getSession();
			JasperReport report = (JasperReport) JRLoader.loadObject(session.getServletContext().getResourceAsStream("/WEB-INF/classes/reports/dc.jasper"));

			
			JasperPrint prt = JasperFillManager.fillReport(report,parms,new JRBeanArrayDataSource(lst.toArray()));
			byte[] pdfReport = JasperExportManager.exportReportToPdf(prt);
			 
			
			JRDocxExporter docExporter=new JRDocxExporter();
			ByteArrayOutputStream docStream=new ByteArrayOutputStream();
			docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,prt);
			docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,docStream);
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docExporter.exportReport();
			pdfReport = docStream.toByteArray();
		
		
			
			
			// saving quotation pdf in database
			logger.info("the bus object is"+bus);
			logger.info("the bus object is"+bus.getBusinessId());
			
			AttachmentHistory attachment=new AttachmentHistory("application/msword",bus,Constants.DELIVERY_CHALLAN,pdfReport,op.getRefNum(),Constants.DELIVERY_CHALLAN+op.getRefNum(),new java.util.Date());
			
			
			
			
			String s=Constants.ST_GENERATED_DC;
			int rid=OpportunityDAO.getSingleInstance().getByRefNo(busid, refno).getId();
			try{
				dcDAO.insert(dc);
				OpportunityDAO.getSingleInstance().updateStatus(busid, s,rid);
				attachmentDAO.insert(attachment);
				System.out.println("Delivery challan Successfully Inserted.");
			}catch(Exception e){
				e.printStackTrace();
				System.out.println("Delivery challan inserting failed.");
			}
			model=new ModelAndView("/jsp/DchallanPDF.jsp");
			model.addObject("invoiceno",Constants.DELIVERY_CHALLAN+op.getRefNum());
			model.addObject("resmsg","Sucesssfully Created   With Challan Number"+op.getRefNum());
			model.addObject("menuName","invoice");
			model.addObject("submenu","invoice");
		return model;
	}
	@RequestMapping("/get_history.do")
	public String htmlReport(HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus=(Business)session.getAttribute("business");
		String quotno=request.getParameter("quotid");
		AttachmentHistory att=attachmentDAO.getAttachmentHistoryByRefno(bus.getBusinessId(),Constants.DELIVERY_CHALLAN,quotno.trim());
		logger.info("the quotation no is "+quotno.trim());
		logger.info("the business id is  "+bus.getBusinessId());
		byte[] pdfReport =att.getFileBlob();
		logger.info("the length of pdf is"+pdfReport.length);
		logger.info("the length of pdf is"+pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		response.setContentType("application/msword");
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close(); 
		return null;
	   
	}

}
